<template>
  <div>
    <jc-bar :prve-btn="true" @prve="$router.push({ path: 'My' })"></jc-bar>
    <v-main>
      <v-container>
        <v-form ref="userinfoForm" style="padding: 10px; box-sizing: border-box">
          <v-row>
            <v-col :cols="12" class="d-flex justify-center">
              <v-avatar>
                <img :src="avatarUrl" />
              </v-avatar>
            </v-col>
            <v-col :cols="12">
              <v-file-input
                :rules="[rules.file, rules.required]"
                accept="image/png, image/jpeg, image/bmp"
                placeholder="Pick an avatar"
                prepend-icon="mdi-camera"
                :label="t('from.Avatar')"
                @change="handlerFileChange"
                :loading="fileLoading"
                @click:clear="handlerFileClear"
              ></v-file-input>
            </v-col>
            <v-col :cols="12">
              <v-text-field
                prepend-icon="mdi-account"
                :label="t('from.NickName')"
                v-model="nickName"
                :rules="[rules.required]"
              ></v-text-field>
            </v-col>
            <v-col :cols="12">
              <v-btn class="float-end" text color="blue darken-1" @click="update">{{ t("button.alert") }}</v-btn>
            </v-col>
          </v-row>
        </v-form>
      </v-container>
    </v-main>
  </div>
</template>

<script>
import JcBar from "../../layout/JcBar";
import { hasLoginState } from "../../api/cloudbase-login";
import { mapGetters } from "vuex";
import { cloudbaseUpload } from "../../api/cloudbase-api";
export default {
  name: "index",
  components: {
    JcBar,
  },
  computed: {
    ...mapGetters(["t", "GET_USER"]),
  },
  data() {
    return {
      rules: {
        file: (value) => !value || value.size < 2000000 || "Avatar size should be less than 2 MB!",
        email: (value) => {
          const pattern =
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
          return pattern.test(value) || this.t("from.InvalidEmail");
        },
        required: (value) => !!value || this.t("from.required"),
      },
      nickName: "",
      avatarUrl: "",
      fileLoading: false,
      file: null,
    };
  },
  mounted() {
    this.init();
  },
  methods: {
    handlerFileChange(file) {
      if (!file) {
        this.avatarUrl = this.GET_USER.avatarUrl;
        return;
      }
      this.avatarUrl = URL.createObjectURL(file);
      this.file = file;
    },
    update() {
      if (this.$refs.userinfoForm.validate()) {
        this.$jcLoading.show();
        this.filecloudupload()
          .then(() => {
            hasLoginState()
              .user.update({
                nickName: this.nickName, // 昵称，不超过 45 个字符
                avatarUrl: this.avatarUrl, // 头像地址，不超过 255 个字符
              })
              .then(() => {
                this.$jcLoading.close();
                this.$jcmsg({ msg: this.t("from.UpdateSucceeded") }).show();
                this.$store.commit("SET_LOGIN_STATE", hasLoginState());
              })
              .catch(() => {
                this.$jcLoading.close();
                this.$jcmsg({ msg: this.t("from.UpdateFailed") }).show();
              });
          })
          .catch(() => {
            this.$jcLoading.close();
          });
      }
    },
    init() {
      this.nickName = this.GET_USER.nickName;
      this.avatarUrl = this.GET_USER.avatarUrl;
    },
    //上传文件清除事件
    handlerFileClear() {
      this.avatarUrl = this.GET_USER.avatarUrl;
    },
    //文件云上传
    filecloudupload() {
      let reg = /(\.\w+)$/;
      let cloudPath = "avatar/" + this.GET_USER.uid + this.file.name.match(reg)[0];
      return new Promise((resolve, reject) => {
        cloudbaseUpload(cloudPath, this.file)
          .then((res) => {
            this.avatarUrl = res.download_url + "?a=" + Date.now();
            resolve(res.download_url + "?a=" + Date.now());
          })
          .catch((error) => {
            console.log(error);
            reject(error);
            this.$jcmsg({
              msg: this.t("from.AvatarUploadFiled"),
              type: "error",
            }).show();
          });
      });
    },
  },
};
</script>

<style scoped></style>
